package org.csu.mypetstore_seller.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore_seller.domain.Category;
import org.csu.mypetstore_seller.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@Controller
@Slf4j
@RequestMapping(value = "/category")
public class CategoryController {

    @Autowired
    HttpSession httpSession;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/view")
    public String categoryView(Model model){
        log.info("访问分类列表页面");
        //获取所有分类数据并且传给前端
        model.addAttribute("categoryList",categoryService.getCategory());
        return "catalog/category";
    }

    @GetMapping("/addView")
    public String addView(){
        log.info("访问商品管理页面");
        return "catalog/newCategory";
    }

    @GetMapping("/delete")
    public void delete(@RequestParam("name") String name, HttpServletResponse response) throws IOException {
        log.info("删除分类，分类名称：{}", name);
        categoryService.deleteCategoryByName(name);
        response.sendRedirect("/category/view");
    }

    //添加新分类
    @PostMapping("/add")
    public void addCategory(@RequestParam("name") String name, HttpServletResponse response) throws IOException {
        log.info("添加新分类，分类名称：{}", name);
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("名字不能为空");
        }
        Category category=new Category();
        category.setName(name);
        category.setCatid(name.toUpperCase());//生成大写ID
        category.page= "<image src=\"../images/"+name+"_icon.gif\"><font size=\"5\" color=\"blue\"> Reptiles</font>";

        category.setDeleteFlag(0);//默认为0，代表着未删除
        categoryService.insertCategory(category);//存到数据库内部
        log.info("分类{}添加成功", name);

        response.sendRedirect("/category/view");
    }
}
